package spzx.auth;

import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.model.vo.common.Result;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import utils.SysUserThreadLocal;

import java.util.concurrent.TimeUnit;


@Component
public class SysUserAuthInterceptor implements HandlerInterceptor {

    //注入redisTemplate
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //System.out.println("经过拦截器" + request.getRequestURI() + "," + request.getMethod());
        //1.跨域请求的预检请求直接放行即可
        String requestMethod = request.getMethod();//当前的请求类型
        //if(requestMethod.equals("OPTIONS"))跟下边这个是一样的
        if ("OPTIONS".equals(requestMethod)) {
            return true;//跨域请求的预检请求直接放行即可。
        }

        System.out.println("拦截器--> preHandle方法-->" + Thread.currentThread().getName());

        //2.判断当前请求是否需要登录
        //获取请求头中的token
        String token = request.getHeader("token");
        //利用token拼接redis中缓存的key
        String key = "user:login:" + token;
        //根据key查询redis的用户信息
        String jsonString = stringRedisTemplate.opsForValue().get(key);
        //将redis中的json字符串转换成sysUser对象
        SysUser sysUser = JSON.parseObject(jsonString, SysUser.class);

        //若sysUser为空，则说明token无效，返回结果
        if(sysUser == null){
            Result result = Result.build(null, ResultCodeEnum.LOGIN_AUTH);
            String jsonResult = JSON.toJSONString(result);

            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");

            response.getWriter().write(jsonResult);
            return false;
        }

        //3.将redis中用户信息ttl设置为30min
        stringRedisTemplate.expire(key, 24, TimeUnit.HOURS);

        //4.使用工具类共享sysUser
        SysUserThreadLocal.setSysUser(sysUser);

        //放行
        return true;
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清除共享变量
        SysUserThreadLocal.removeSysUser();
    }


    public static void main(String[] args) {
        String jsonString = null;
        SysUser sysUser = JSON.parseObject(jsonString, SysUser.class);
        System.out.println(sysUser);
    }
}
